package com.zhibang.controller;

import com.alibaba.fastjson2.JSONObject;
import com.zhibang.dto.LoginDTO;
import com.zhibang.entity.Users;
import com.zhibang.mapper.UsersMapper;
import com.zhibang.service.UsersService;
import com.zhibang.util.JwtUtil;
import com.zhibang.util.RedisUtil;
import com.zhibang.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


@Tag(name = "用户模块")
@RestController
public class UserController {
    // 用来做登录的对象
    @Resource
    AuthenticationManager am;
    @Resource
    RedisUtil redisUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("login")
    @Operation(summary = "用户登录",description = "返回用户令牌,用户名与头像")
    public Result login(@RequestBody LoginDTO dto){
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(dto.getUsername(),dto.getPassword());
        Authentication auth = am.authenticate(token);
        // 获取登录后的用户信息
        Users user = (Users) auth.getPrincipal();
        // 生成令牌
        String jwt = JwtUtil.generateToken(user.getUserId());
        // 把用户存储在redis中 过期时间为30分钟
        redisUtil.set("token:"+jwt,user,60*30);
        // 创建返回对象
        JSONObject json = new JSONObject();
        json.put("token",jwt);
        json.put("username",user.getUsername());
        json.put("tx",user.getAvatar());
        return Result.data(json);
    }
    //注册
    @Resource
    UsersService usersService;
    @Resource
    UsersMapper usersMapper;
    @PostMapping("register")
    @Operation(summary = "用户注册")
    public Result register(@RequestBody Users user){
        Integer i = usersMapper.selectByEmail(user.getEmail());
        if(i !=null&&i.intValue()>0 ){
            return Result.fail("邮箱已存在");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return Result.data(usersService.save(user));
    }
}
